<template>
  <div class="app-main-container">
    <!-- <div class="app-main-title">会员配置</div> -->
    <div v-if="meta.indexOf('OptionVipAdd') > -1" class="doumee-table-buttons">
      <el-button
        v-if="meta.indexOf('OptionVipAdd') > -1"
        type="primary"
        @click="toAmountAdd(0)"
      >新增</el-button>
    </div>
    <el-table
      ref="table1"
      :data="listAmount"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        label="会员充值固定金额配置"
        prop="name"
        min-width="300"
      />
      <el-table-column align="center" label="状态" min-width="200">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isAllow"
            v-preventReClick
            :active-value="'1'"
            :inactive-value="'0'"
            :disabled="meta.indexOf('OptionVipEdit') == -1"
            @change="changeConfig($event, scope.row.id, 'isAllow', 'amount')"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="排序码"
        prop="sort"
        min-width="200"
      />
      <el-table-column align="center" width="1" />
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        min-width="200"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="meta.indexOf('OptionVipEdit') > -1"
              v-preventReClick
              type="text"
              @click="toAmountAdd(1, scope.row)"
            >编辑</el-button>
            <el-button
              v-if="meta.indexOf('OptionVipDel') > -1"
              v-preventReClick
              type="text"
              style="color: red"
              @click="toDeleteAmount(scope.row.id)"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex-cc doumee-pagination">
      <el-pagination
        :hide-on-single-page="true"
        background
        layout="prev, pager, next"
        :total="total"
      />
    </div>

    <el-table
      ref="table2"
      :data="listDiscount"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        label="优惠改价"
        prop="name"
        min-width="300"
      />
      <el-table-column align="center" label="是否支持修改">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isEdit"
            v-preventReClick
            :active-value="'1'"
            :inactive-value="'0'"
            @change="changeConfig($event, scope.row.id, 'isEdit', 'discount')"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="说明"
        prop="description"
        min-width="300"
      />
    </el-table>

    <div style="height: 40px" />

    <el-table
      ref="table3"
      :data="listWX"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column align="center" label="微信场地" width="500">
        <template slot-scope="scope">
          <div class="flex-c">
            <div style="flex: 1; text-align: left; display: block">
              {{ scope.row.name }}
              <el-button
                v-if="
                  meta.indexOf('OptionVipBook') > -1 &&
                    scope.row.code === 'APP_SITE_BOOK_DAY'
                "
                type="primary"
                @click="isShowMemSiteCon = true"
              >会员订场配置</el-button>
            </div>
            <el-input
              v-model="scope.row.value"
              style="width: 120px"
              placeholder=""
              size="normal"
              @change="editWXItem(scope.row)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="说明"
        prop="description"
        min-width="500"
      />
    </el-table>

    <!-- 新增节假日配置 -->
    <el-dialog
      :close-on-click-modal="modalDialog"
      :lose-on-press-escape="modalDialog"
      title="会员充值固定金额配置"
      :visible.sync="showAmountAddData"
    >
      <el-form
        ref="refForm"
        :rules="rules"
        :model="amountAddData"
        label-width="100px"
      >
        <el-form-item label="固定金额" prop="name">
          <el-input v-model="amountAddData.name" maxlength="10" autocomplete="off" onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" oninput="if(value<0) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
            v-model="amountAddData.isAllow"
            :active-value="'1'"
            :inactive-value="'0'"
          />
        </el-form-item>
        <el-form-item label="排序码" prop="sort">
          <el-input v-model="amountAddData.sort" maxlength="10" autocomplete="off" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAmountAddData = false">取 消</el-button>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="formOnSubmit('refForm')"
        >确 定</el-button>
      </div>
    </el-dialog>

    <!-- 会员订场配置 -->
    <el-dialog
      :close-on-click-modal="modalDialog"
      :lose-on-press-escape="modalDialog"
      title="会员订场配置"
      :visible.sync="isShowMemSiteCon"
      width="800px"
    >
      <span
        class="warnningTip"
      >支持按会员等级进行个性化配置会员的可提前预定天数，单位天；</span>
      <div class="memSite_wrap">
        <div v-for="item in cardList" :key="item.id" class="item">
          <div class="label">{{ item.cardName }}：</div>
          <el-input
            v-model="item.value"
            oninput="value=value.replace(/^(0+)|[^\d]+/g, '').slice(0, 5)"
            class="w200"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowMemSiteCon = false">取 消</el-button>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="memSiteSub"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  memberSiteConfigSet,
  cardList,
  configList,
  configUpdate,
  configAdd,
  configDelete
} from '@/api'
export default {
  name: 'OptionVip',
  data() {
    return {
      modalDialog: this.$store.state.app.dialog,
      subLoading: false,
      meta: [],
      listAmount: [],
      listDiscount: [],
      listWX: [],
      cardList: [],
      isShowMemSiteCon: false,
      memSiteConfig: {},
      pagination: {
        firstQueryTime: new Date(),
        page: 1,
        rows: 10
      },
      total: 0,
      amountAddEdit: 0,
      showAmountAddData: false,
      amountAddData: {
        name: '',
        isAllow: '1',
        sort: '',
        type: '5'
      },
      rules: {
        name: [{ required: true, message: '请输入固定金额', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序码', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getConfig()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table1.doLayout()
      this.$refs.table2.doLayout()
      this.$refs.table3.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table1.doLayout()
      this.$refs.table2.doLayout()
      this.$refs.table3.doLayout()
    })
  },
  methods: {
    // 获取配置项
    async getConfig() {
      // 会员充值配置
      configList({ param: { type: '5' }}).then((res) => {
        this.listAmount = res.recordList
        this.total = res.totalCount
        const t = res.totalCount / 10
        const count = Number(t.toFixed(0)) + (t - t.toFixed(0) > 0 ? 1 : 0)
        this.total = count * 10
      })
      // 优惠改价/赠送金额配置
      configList({ param: { type: '6' }}).then((res) => {
        if (res.errorCode === '000000') {
          this.listDiscount = res.recordList
        }
      })
      // 微信场地配置
      configList({ param: { type: '7' }}).then((res) => {
        if (res.errorCode === '000000') {
          this.listWX = res.recordList
        }
      })
      const cardRes = await cardList({ param: { type: '1' }})
      this.cardList = cardRes.recordList.map((item) => {
        item.value = null
        return item
      })
      // 会员场地配置项
      configList({ param: { type: '20' }}).then((res) => {
        if (res.errorCode === '000000') {
          this.memSiteConfig = res.recordList
          this.cardList.forEach((item) => {
            this.memSiteConfig.forEach((item2) => {
              if (item.id === item2.name) {
                item.value = item2.value
              }
            })
          })
        }
      })
    },
    memSiteSub() {
      const temp = this.cardList.filter((i) => i.value)
      if (temp.length === 0) { return this.$message.warning('请输入会员对应可提前订场天数') }
      const list = temp.map((item) => {
        return {
          name: item.id,
          value: item.value
        }
      })

      this.subLoading = true
      memberSiteConfigSet({ param: { list }}).then(
        (res) => {
          this.subLoading = false
          if (res.errorCode !== '000000') return
          this.$message.success('配置成功')
          this.isShowMemSiteCon = false
          this.getConfig()
        },
        () => {
          this.subLoading = false
        }
      )
    },
    // getCardList() {
    //   cardList({ param: { type: '1' }}).then(res => {
    //     this.cardList = res.recordList || []
    //   })
    // },
    // 添加/编辑会员充值配置
    toAmountAdd(type, data) {
      this.amountAddEdit = type
      this.showAmountAddData = true
      if (type) {
        this.amountAddData = data
      }
    },
    formOnSubmit(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.confirmAmountAdd()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 确认添加/编辑会员充值配置
    confirmAmountAdd() {
      const { amountAddData: param, amountAddEdit } = this
      if (amountAddEdit) {
        this.subLoading = true
        // 编辑
        configUpdate({ param }).then(
          (res) => {
            this.subLoading = false
            if (res.errorCode === '000000') {
              this.getConfig()
              this.showAmountAddData = false
              this.amountAddData = {
                name: '',
                isAllow: '1',
                sort: '',
                type: '5'
              }
            }
          },
          () => {
            this.subLoading = false
          }
        )
      } else {
        // 新增
        configAdd({ param }).then(
          (res) => {
            this.subLoading = false
            if (res.errorCode === '000000') {
              this.getConfig()
              this.showAmountAddData = false
              this.amountAddData = {
                name: '',
                isAllow: '1',
                sort: '',
                type: '5'
              }
            }
          },
          () => {
            this.subLoading = false
          }
        )
      }
    },
    // 删除会员充值配置
    toDeleteAmount(id) {
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          configDelete({ param: { id }}).then((res) => {
            if (res.errorCode === '000000') {
              this.$message.success('删除成功')
              this.getConfig()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 切换 会员充值配置状态、优惠改价/赠送金额是否支持修改
    changeConfig(data, id, name, type_) {
      const param = { id }
      param[name] = data
      switch (type_) {
        case 'amount':
          param.type = '5'
          break

        case 'discount':
          param.type = '6'
          break

        default:
          break
      }
      configUpdate({ param }).then((res) => {
        if (res.errorCode === '000000') {
          this.$message.success('修改成功')
        }
      })
    },
    // 修改微信场地
    editWXItem(param) {
      configUpdate({ param }).then((res) => {
        if (res.errorCode === '000000') {
          this.$message.success('修改成功')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.memSite_wrap {
  display: flex;
  flex-wrap: wrap;
  .item {
    width: 50%;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    .label {
      flex: 1;
      text-align: right;
    }
  }
}
</style>
